//
//  HMBaseTableViewController.swift
//  HealthMonitoring
//
//  Created by 珠海正杰 on 2018/4/8.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import MJRefresh // 依赖有一点严重

private let imageError = UIImage(named: "Cry") // UIImage(named: "Cry")
private let imageLoading = UIImage(named: "Loading")
let TIPS_LOADING = "加载中..." // "加载中..."
let TIPS_LOAD_FAIL = "加载失败" // "加载失败"
let TIPS_TAP_RELOAD = "点击加载" // "点击重新加载"
let TIPS_NETWORK_EXCEPTION = "网络不是很给力,加载就失败了.."
let TIPS_CLEANING_CACHE = "正在清除缓存,请稍候"  //感觉木有用


public typealias HMTableViewController = HMBaseTableViewController
public class HMBaseTableViewController: UITableViewController {
    // MARK: - 变量
    public var controllerInfo = NSDictionary() // 给控制器的数据
    public var page = 0
    public var shouldHideNavigationBar: Bool = false
    private var shouldShowEmptyStatus: Bool = true
    private var statusText = TIPS_LOADING
    private var statusDesciption = TIPS_TAP_RELOAD
    private var statusImage = imageLoading
    
    
    public func load() {
        
    }
    override public func viewDidLoad() {
        super.viewDidLoad()
        load()
        self.tableView.mj_header = MJRefreshNormalHeader(refreshingBlock:{
            self.request(type: "header")
        })
        self.tableView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {
            self.requestMore()
        })
       // view.addSubview(<#T##view: UIView##UIView#>)
       self.tableView.clearExtraLines()
        
    }
    override public func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
    override public func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if shouldHideNavigationBar {
            self.navigationController?.setNavigationBarHidden(true, animated: animated)
        }else {
            fixNavigationBarColor(animated: animated)
        }
        
    }
    override public func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    // 测试
    override public func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let sonView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: view.frame.width, height: 200))
        sonView.backgroundColor = UIColor.blue
        scrollView.bringSubview(toFront: sonView)
    }
    // MARK: - refresh
    // 停止刷新
    public func endRefreshing(type:String) {
        if type == "header" {
          self.tableView.mj_header.endRefreshing()
        }else {
          self.tableView.mj_footer.endRefreshing()
        }
    }
    // 停止刷新 没有数据了
    public func footerNoData() {
//        self.tableView.mj_footer.endRefreshingWithNoMoreData()
    }
    // 请求方法
    /**
     * type - header or footer
     */
    public func request(type: String) {
        endRefreshing(type: type)
    }
    public func requestMore() {
        footerNoData()
    }
    
    
    // MARK: - Table view data source
    override public func numberOfSections(in tableView: UITableView) -> Int {
        return 0
    }

    override public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    override public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
    public override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
    override public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
        let cell = cellForRow(atIndexPath: indexPath as NSIndexPath)  // 这样会没有用到这个cell
        if let hmCell =  cell as? HMTableViewCell {
          hmCell.setup()
          hmCell.rootViewController = self
          hmCell.indexPath = indexPath
          return hmCell
        }
        return cell
        
    }
    override public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
    @discardableResult public func cellForRow(atIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
    
    // 全部刷新
    public func reloadData() {
        self.tableView.reloadData()
    }
    
    

    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension UIViewController {
    // 固定导航条颜色
    func fixNavigationBarColor(animated: Bool) {
        //        assertionFailure("lib not been imported")
        
        // FIXME:
        //        self.navigationController?.navigationBar.translucentWith(COLOR_WHITE)
        //        self.navigationController?.navigationBar.translucent = false
        //
        //        self.navigationController?.setNavigationBarHidden(false, animated: animated)
        //        self.navigationController?.navigationBar.setBackgroundImage(nil, forBarMetrics: UIBarMetrics.Default)
    }
}

public extension UITableView {
    public func clearExtraLines() {
        let size = CGSize.zero
        self.tableFooterView = UIView.init(frame: CGRect.init(origin: CGPoint.zero, size: size))
    }
    public func setInsetsTop(top: CGFloat) {
        let insets = UIEdgeInsets.init(top: top, left: contentInset.left, bottom: contentInset.bottom, right: contentInset.right)
        setInsets(insets: insets)
    }
    public func setInsets(top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat) {
        let insets = UIEdgeInsets(top: top, left: left, bottom: bottom, right: right)
        setInsets(insets: insets)
    }
    
    /**
     修正顶栏位置
     
     - parameter insets: top: 0, left: 0, bottom: 0, right: 0
     */
    public func setInsets(insets: UIEdgeInsets) {
        self.contentInset = insets;
        self.scrollIndicatorInsets = insets;
    }
    
}













